package com.sc.interceptor;

import com.sc.config.JWTProperties;
import com.sc.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
@RequiredArgsConstructor
public class JWTInterceptor implements HandlerInterceptor {

    private final JWTProperties jwtProperties;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 判断档期那拦截到的是否为Controller
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 判断如果请求的类是swagger的控制器，放行
        if (((HandlerMethod) handler).getBean().getClass().getName().equals("springfox.documentation.swagger.web.ApiResourceController")) {
            return true;
        }

        // 获取令牌
        String token = request.getHeader(jwtProperties.getToken());

        // 校验
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JWTUtil.parseJWT(jwtProperties.getSecretKey(), token);
            //3、通过，放行
            log.info("校验通过");
            return true;
        } catch (Exception e) {
            log.info("未通过");
            response.setStatus(401);
            return false;
        }
    }
}
